package com.lengxf.flink.sink;

import com.lengxf.flink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.connector.source.util.ratelimit.RateLimiterStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.datagen.source.DataGeneratorSource;
import org.apache.flink.connector.datagen.source.GeneratorFunction;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

/**
 * 消息写入mysql
 *
 * @author Lengxf
 */
public class SinkCustom {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        env.enableCheckpointing(2000, CheckpointingMode.EXACTLY_ONCE);
        DataGeneratorSource<WaterSensor> source = new DataGeneratorSource<>(
                (GeneratorFunction<Long, WaterSensor>) aLong -> new WaterSensor(String.valueOf(aLong), Math.toIntExact(aLong), aLong),
                100,
                RateLimiterStrategy.perSecond(1),
                Types.POJO(WaterSensor.class)
        );
        //数据源消息
        DataStreamSource<WaterSensor> waterSensorSource = env.fromSource(source, WatermarkStrategy.noWatermarks(), "data-generator");

        //来一条数据便会处理一次
        waterSensorSource.addSink(new MySinkFun());
        env.execute();
    }

    public static class MySinkFun extends RichSinkFunction<WaterSensor> {
        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            //在这里建立链接
        }

        @Override
        public void close() throws Exception {
            super.close();
            //线程结束销毁
        }

        @Override
        public void invoke(WaterSensor value, Context context) throws Exception {
            super.invoke(value, context);
        }
    }


}
